package com.nineclock.auth.processor;

import com.nineclock.auth.entity.IntegrationAuthenticationEntity;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.model.dto.SysUserDTO;
import com.nineclock.system.feign.SysUserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 用户账号和密码登录验证
 */

@Component
public class UsernameAndPasswordAuthenticationProcessor implements AuthenticationProcessor {
    @Autowired
    private SysUserFeign sysUserFeign;


    @Override
    public SysUserDTO authenticate(IntegrationAuthenticationEntity entity) {
        //获取请求参数的用户名和密码
        String username = entity.getAuthParameter("username");
        String password = entity.getAuthParameter("password");
        //验证健壮性
        if (username==null||password== null) {
            throw  new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        //去数据库校验用户账号和密码
        SysUserDTO userDTO = sysUserFeign.queryUser(username).getData();

        if (userDTO==null) {
            throw new NcException(ResponseEnum.INVALID_USERNAME_PASSWORD);
        }


        return userDTO;
    }

    @Override
    public boolean support(IntegrationAuthenticationEntity entity) {
        if (entity!=null&&StringUtils.isEmpty(entity.getAuthType())) {
            return true;
        }

        return false;
    }
}